package com.rocpenghua.excel.easyexcel;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;

import java.util.List;

/**
 * 自适应列宽
 * @author pengp
 * @date 2024年02月27日 17:10
 */
@RequiredArgsConstructor
public class DefaultCellWriteWidthConfig extends AbstractColumnWidthStyleStrategy {
    /**
     * 默认高度
     */
    private static final Integer DEFAULT_WIDTH = 20;

    @Override
    protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer integer, Boolean isHead) {
        boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);
        if (needSetWidth) {
            // 单元格文本长度大于60换行
            Sheet sheet = writeSheetHolder.getSheet();
            sheet.setColumnWidth(cell.getColumnIndex(), DEFAULT_WIDTH * 256);
        }
    }
}
